<?php

namespace App\Http\Controllers;

use App\Service\Captcha;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

class AuthController extends Controller
{
    public function __construct()
    {
        $this->middleware('jwt.verify', ['except' => ['login', 'register','sendCode']]);
    }

    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'mobile' => 'required|regex:/^1[34578][0-9]{9}$/',
            'code' => 'required|numeric'
        ]);

        if ($validator->fails()) {
            return renderError($validator->errors()->first());
        }

        $credentials = $request->only('mobile');
        $credentials['password'] = '123456';

        // 校验验证码
        if (!checkCaptcha($credentials['mobile'], $request->code)) {
            return renderError('验证码错误');
        }
        $mobile = $credentials['mobile'];
        //判断用户是否存在 如果没有则创建
        $user = User::where('mobile', $mobile)->first();
        if (!$user) {
            User::insert([
                'name' => '用户' . $mobile,
                'mobile' => $mobile,
                'password' => bcrypt($credentials['password'])
            ]);
        }

        try {
            if (!$token = JWTAuth::attempt($credentials)) {
                return renderError('手机号错误或者用户不存在');
            }
        } catch (JWTException $e) {
            return renderError('登录失败');
        }

        $user = auth('api')->user();

        return renderSuccess([
            'token' => 'bearer ' . $token,
            'token_type' => 'bearer',
            'expires_in' => config('jwt.ttl') * 60,
        ]);
    }

    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|between:2,100',
            'email' => 'required|string|email|max:100|unique:users',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }

        $user = User::create(array_merge(
            $validator->validated(),
            ['password' => bcrypt($request->password)]
        ));

        return response()->json([
            'message' => '用户注册成功',
            'user' => $user
        ], 201);
    }

    public function logout()
    {
        auth()->logout();
        return response()->json(['message' => '成功退出']);
    }

    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => config('jwt.ttl') * 60
        ]);
    }

    // 发送验证码
    public function sendCode()
    {
        $code = rand(1000, 9999);

        try {
            $mobile = request('mobile');
            $key = 'captcha-' . $mobile;
            // 不能重复发送
            if (Cache::has($key)) {
//                return renderError('请勿重复发送');
            }

            $expiredAt = now()->addSeconds(60 * 5);
            $value = ['code' => $code, 'expired_at' => $expiredAt];
            Cache::put($key, $value, $expiredAt);// 发送验证码
            Captcha::Send($mobile, $code);
        } catch (\Exception $e) {
            return renderError('发送失败');
        }

        return renderSuccess([], '发送成功');
    }

    public function user()
    {
        return response()->json(auth()->user());
    }
}
